import { useState, useEffect } from 'react';
import { Space, Tag, Pagination,Table, Button, Modal, Form, Input, message,TreeSelect,Avatar  } from 'antd';
import {getUser,postUser,getTeacher,postTeacher } from '../../api/user';
import Action from '../Action';
import { UserOutlined } from '@ant-design/icons';
import {uploadAvatar} from '../../api/user';
import { useAuth, avatarBaseUrl } from '../../context/AuthProvider';

const { CheckableTag } = Tag;
const { SHOW_PARENT } = TreeSelect;

  
 
const Teacher = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [teacherList,setTeacherList]=useState([]);
    const { user, setUser } = useAuth();
    const [avatar, setAvatar] = useState("");

    const [value, setValue] = useState();
    const onChange = (newValue) => {
      console.log(newValue);
      setValue(newValue);
    };
    const handleData = (data) => {
      // 处理回传的数据
      console.log(data);
      let list= [...teacherList]
      for(let i =0;i<list.length;i++){
        if(list[i].tid==data.tid){
            if(data.tname==""){
                list.splice(i, 1);
            }
            else{
                list[i]=data;
            }
            
            break;
        }
      }
      setTeacherList(list)
    };
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleCancel = () => {
        setAvatar("")
        setIsModalOpen(false);
    };
   const deleteTeacher=(e,record)=>{
    console.log(record)
   }
    // const [selectedTags, setSelectedTags] = useState('');
    // const [news, setNews] = useState([]);
    // // const [total, setTotal] = useState(0);
    // // const [page, setPage] = useState(1);

    useEffect(() => {
        getTeacher()
            .then(res => {
                console.log(res,"teacher");
           
                setTeacherList(res.result)
                // setTotal(res.data.totalElements);
            })
    }, [])
    const onFinish = (values)=>{
        getUser({id:values.tid}).then((res)=>{
            if(res.result.length==0){
                const userdata={
                  username:values.tname,
                  password:values.password,
                  loginid:values.tid,
                  power:2,
                }
                console.log(values)
                postUser({...userdata,avatar:avatar})
        
                postTeacher({...values})
                .then(res=>{
                    console.log(res)
                    setTeacherList([...teacherList,{...values}])    
                    
                    setIsModalOpen(false);
                    message.success('增加教师成功')
                 
                    
                })
              }
        
              else{
                message.error('存在相同学号/教工号用户！')
              }
        })
  
        
  }
  const columns = [
    {
      title: '教工号',
      dataIndex: 'tid',
      key: 'tid',
    },
    {
      title: '姓名',
      dataIndex: 'tname',
      key: 'tname',
    },
    {
      title: '所属学院',
      dataIndex: 'subject',
      key: 'subject',
    },
    {
        title: 'Action',
        key: 'action',
        render: (_, record) => (
            <Action message={{...record,avatar}} type={0} onData={handleData}/>
        //   <Space size="middle">
        //     <Action />
        //     <a onClick={showModal}>修改</a>
        //     <a  onClick={(e)=>deleteTeacher(e,record)}>删除{record.tid}</a>
        //   </Space>
        ),
      },
  ];
  const change = (e) => {
    const avatarData = new FormData()
    console.log(e)
    avatarData.append('file', e.target.files[0]);
    console.log(avatarData);
    uploadAvatar(avatarData)
        .then(res => {
            setAvatar(res.url)

        })
}
  class TreeNode {
    constructor(id, name) {
      this.id = id;
      this.name = name;
      this.children = [];
    }
  
    addChild(child) {
      this.children.push(child);
    }
  }
  
  function generateTree(studentList) {
    const schoolNode = new TreeNode(0, 'School');
  
    studentList.forEach((student) => {
      const { grade, className, name } = student;
  
      let gradeNode = schoolNode.children.find((node) => node.name === grade);
      if (!gradeNode) {
        gradeNode = new TreeNode(grade, grade);
        schoolNode.addChild(gradeNode);
      }
      
      let classNode = gradeNode.children.find((node) => node.name === className);
      if (!classNode) {
        classNode = new TreeNode(className, className);
        gradeNode.addChild(classNode);
      }
    //   const classNode = new TreeNode(className, className);
    //   gradeNode.addChild(classNode);
  
      const studentNode = new TreeNode(student.id, name);
      classNode.addChild(studentNode);
    });
  
    return schoolNode;
  }
  
  // 示例数据

    return (
        <>
            <div>
            <Button
                type="primary"
                onClick={showModal}
            >
                新增教师
            </Button>
            </div>
          
            <Table dataSource={teacherList} columns={columns} scroll={{ y: 280 }} />
            <Modal
                title="新增教师"
                open={isModalOpen}
                footer={null}
                onCancel={handleCancel}
            >
                <Form
                    name="basic"
                    layout='vertical'
                    // style={{ width: 400, margin: '50px auto' }}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                      {/* <input onChange={change} style={{ display: 'none' }} id='avatar' type="file" />
                    <label htmlFor="avatar">
                        <Avatar src={avatar} size={40} icon={<UserOutlined />} />
                    </label> */}
                    <Form.Item
                        label="教工号"
                        name="tid"
                        rules={[
                            {
                                required: true,
                                message: '请输入教工号',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="姓名"
                        name="tname"
                        rules={[
                            {
                                required: true,
                                message: '请输入教师姓名',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="学院"
                        name="subject"
                        rules={[
                            {
                                required: true,
                                message: '请输入教师所属学院',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: '请输入设定密码',
                            },
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item>
                        <Button
                            block
                            shape='round'
                            type="primary"
                            htmlType="submit"
                        >
                            新增教师
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};
export default Teacher;